import { useAdminStore } from '@/stores/admin-store';
import { useMenuStore } from '@/stores/menu-store';
import { useGlobalStore } from '@common/store/global-store';
import { useWebSocketStore } from '@/stores/websocket-store';
import { login } from '@common/helper/system';
import { useRouter } from '@common/router';
import { FuncUtil } from '@jecloud/func';
import { openAdminMenu } from '@/hooks/use-menu';
import { changeUserConfig } from './use-plan';
export function initGlobalEvents() {
  const globalStore = useGlobalStore();
  const adminStore = useAdminStore();
  const menuStore = useMenuStore();
  const webSocketStore = useWebSocketStore();
  // 登录事件
  globalStore.on('login', () => {
    const router = useRouter();
    // 登录成功，跳转历史路由
    if (globalStore.historyRoute) {
      router.push({ path: globalStore.historyRoute });
      globalStore.historyRoute = ''; // 清空历史
    } else {
      // 登录成功，跳转首页
      const route = router.currentRoute.value;
      const { plan = globalStore.activePlan, layout = 'main' } = route.params;
      router.push({
        name: 'PlanHome',
        params: { plan, layout },
      });
    }
    return false;
  });
  // 退出事件
  globalStore.on('logout', () => {
    // 路由处理
    const router = useRouter();
    // 退出路由
    const route = router.currentRoute.value;
    router.push({
      name: 'PlanLogin',
      params: { plan: route.params.plan ?? globalStore.activePlan },
    });
    return false;
  });

  /*---------------------------主应用事件，暴露给子应用使用----------------------------*/
  // 登录事件
  adminStore.on('login', login);
  // 登录成功
  adminStore.on('login-success', () => {
    webSocketStore.login();
    changeUserConfig();
  });
  // 退出事件
  adminStore.on('logout', () => {
    adminStore.init = false;
    useMenuStore().logout();
    useWebSocketStore().logout();
  });

  // 打开菜单
  adminStore.on('admin-openmenu', openAdminMenu);

  // 清除缓存
  adminStore.on('admin-cache-clear', ({ type, code }) => {
    switch (type) {
      case 'func':
        FuncUtil.clearFuncCache(code);
        break;
    }
  });
}
